//
//  Fraction.m
//  OC_03_属性_点语法
//
//  Created by wyx on 16/2/26.
//  Copyright © 2016年 Apon. All rights reserved.
//

#import "Fraction.h"

@implementation Fraction
#pragma mark - init
- (instancetype)initWithNumerator:(NSInteger)numerator denominator:(NSInteger)denominator{
    self = [super init];
    if (self) {
        _numerator = numerator;
        _denominator = denominator;
    }
    return self;
}
#pragma mark - 构造器
+ (instancetype)fractionWithNumeration:(NSInteger)numerator denominator:(NSInteger)denominator{
    return [[Fraction alloc] initWithNumerator:numerator denominator:denominator];
}
#pragma mark - 加法
- (Fraction *)addWithFraction:(Fraction *)frac{
    NSInteger newNum = self.numerator * frac.denominator + self.denominator * frac.numerator;
    NSInteger newDeno = self.denominator * frac.denominator;
    //创建分数对象
    Fraction *newFrac = [Fraction fractionWithNumeration:newNum denominator:newDeno];
    return newFrac;
}
#pragma mark - 减法
- (Fraction *)subWithFraction:(Fraction *)frac{
    NSInteger newNum = self.numerator * frac.denominator - self.denominator * frac.numerator;
    NSInteger newDeno = self.denominator * frac.denominator;
    Fraction *newFrac = [Fraction fractionWithNumeration:newNum denominator:newDeno];
    return newFrac;
}
#pragma mark - 乘法
- (Fraction *)mulWithFraction:(Fraction *)frac{
    NSInteger newNum = self.numerator * frac.numerator;
    NSInteger newDeno = self.denominator * frac.denominator;
    Fraction *newFrac = [Fraction fractionWithNumeration:newNum denominator:newDeno];
    return newFrac;
}
#pragma mark - 除法
- (Fraction *)divWithFraction:(Fraction *)frac{
    NSInteger newNum = self.numerator * frac.denominator;
    NSInteger newDeno = self.denominator * frac.numerator;
    Fraction *newFrac = [Fraction fractionWithNumeration:newNum denominator:newDeno];
    return newFrac;
}
#pragma mark - 比较大小
- (void)cmpWithFraction:(Fraction *)frac{
    NSInteger newNum = self.numerator * frac.denominator;
    NSInteger newDeno = self.denominator * frac.numerator;
    //Fraction *newFrac = [Fraction fractionWithNumeration:newNum denominator:newDeno];
    if (newNum < newDeno) {
        NSLog(@" %ld/%ld < %ld/%ld",self.numerator,self.denominator,frac.numerator,frac.denominator);
    }
    else if (newNum > newDeno){
        NSLog(@" %ld/%ld > %ld/%ld",self.numerator,self.denominator,frac.numerator,frac.denominator);
    }
}
#pragma mark - 约分
- (Fraction *)simWithFraction:(Fraction *)frac{
    NSInteger newNum = self.numerator;
    NSInteger newDeno = self.denominator;
    long num = 0;
    if (newNum<=0) {
        newNum = -newNum;
    }
    if (newDeno<=0) {
        newDeno = -newDeno;
    }
    for (long i = (newNum<newDeno?newNum:newDeno); i >0; i--) {
        if (newNum%i == 0 && newDeno%i == 0) {
            num = i;
            break;
        }
    }
    Fraction *newFrac = [Fraction fractionWithNumeration:newNum/num denominator:newDeno/num];
    return newFrac;
}
@end

